package com.it.day1;

import org.junit.Test;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * ClassName: CompletableFutureDemo
 * Description: CompletableFuture测试
 *
 * @Author: csx
 * @Create: 2025/5/7 - 23:42
 * @version: v1.0
 */
public class CompletableFutureDemo {
    @Test
    public void test1() throws ExecutionException, InterruptedException {
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t" + "执行了");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
            }
        });
        System.out.println(future.get());

        System.out.println("继续上课");
    }

    @Test
    public void test2() throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t" + "执行了");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
            }
            return "老师我帮你买到水了";
        });
        System.out.println(future.get());

        System.out.println("继续上课");
    }

    @Test
    public void test3() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
                    System.out.println(Thread.currentThread().getName() + "\t" + "执行了");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                    }
                    return 1;
                }).thenApply(f -> f + 1)    //f表示上一个的输入，在做些操作返回给下一层
                .whenComplete((v, e) -> {   //v表示上一个的输入，e表示是否抛异常
                    if (e == null) {    //null表示没抛，则这里执行异步函数内容
                        System.out.println("异步函数完成了 " + v);
                    }
                }).exceptionally(e -> { //如果上述抛异常了，则会来到这里处理异常相当于catch操作。
                    e.printStackTrace();
                    return null;
                });

        System.out.println("继续上课");

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
        }
    }
}

























